package com.zlsy.thread.volatiledemo;

import lombok.extern.slf4j.Slf4j;

import java.util.concurrent.ArrayBlockingQueue;

/**
 * @author zhouliang
 * @date 2020/2/27 10:29
 */
@Slf4j
public class WrongWayVolatileFixed {
    public static void main(String[] args) throws InterruptedException {
        //非静态的内部类实例化，本体要先实例化
        WrongWayVolatileFixed body = new WrongWayVolatileFixed();

        ArrayBlockingQueue storage = new ArrayBlockingQueue<>(10);
        Producer producer = body.new Producer(storage);
        Thread thread = new Thread(producer);
        thread.start();
        Thread.sleep(1000);

        Consumer consumer = body.new Consumer(storage);
        while (consumer.needMoreNums()) {
            System.out.println(consumer.storage.take() + "已经被消费了");
            Thread.sleep(100);
        }
        thread.interrupt();
        System.out.println("消费者不需要更多的数据了，请生产者停止生产！");
    }

    class Producer implements Runnable {
        ArrayBlockingQueue storage;

        public Producer(ArrayBlockingQueue storage) {
            this.storage = storage;
        }

        @Override
        public void run() {
            try {
                int num = 0;
                while (num <= 10000 && !Thread.currentThread().isInterrupted()) {
                    if (num % 100 == 0) {
                        //当有符合条件的num的时候生产者开始生产放入生产队列，但是只能放十个就阻塞了。
                        storage.put(num);
                        System.out.println(num + "是一百的倍数，放到仓库中了");
                    }
                    num++;
                }
            } catch (InterruptedException e) {
                log.warn("生产者已经停止运行:{}", e);
            } finally {
                System.out.println("生产者停止运行！");
            }
        }
    }

    class Consumer {
        ArrayBlockingQueue storage;

        public Consumer(ArrayBlockingQueue storage) {
            this.storage = storage;
        }

        public boolean needMoreNums() {
            if (Math.random() > 0.95) {
                return false;
            }
            return true;
        }

    }
}
